using Microsoft.AspNetCore.Mvc;

namespace WebApplication3.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class OrderController : ControllerBase
    {
        private OrderContext _orderContext;
        public OrderController(OrderContext context)
        {
            _orderContext = context; // Dependency Injection
        }
        [HttpGet("{id}")]
        public ActionResult<List<Order>> GetById(int id)
        {
            IQueryable<Order> query = _orderContext.orders;
            if (id != null)
            {
                query = query.Where(x => x.Id == id);
            }
            return query.ToList();
        }
        
        [HttpPost(Name = "Post")]
        public ActionResult<Order> PostOrder(Order order)
        {
            try
            {
                _orderContext.orders.Add(order);
                _orderContext.SaveChanges();
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
            return order;
        }
        [HttpDelete("{id}")]
        public ActionResult DeleteOrder(int id)
        {
            try
            {
                var order = _orderContext.orders.FirstOrDefault(x => x.Id == id);
                if (order != null)
                {
                    _orderContext.Remove(order);
                    _orderContext.SaveChanges();
                }
            }
            catch(Exception ex)
            {
                return BadRequest(ex.Message);
            }
            return NoContent();
        }
        [HttpPut]
        public ActionResult<Order> PutCustomer(int id, Order order)
        {
            try
            {
                _orderContext.Entry(order).State = Microsoft.EntityFrameworkCore.EntityState.Modified;
                _orderContext.SaveChanges();
            }
            catch (Exception e)
            {
                string error = e.Message;
                if (e.InnerException != null)
                    error = e.InnerException.Message;
                return BadRequest(error);
            }
            return NoContent();
        }
    }
}